package com.bright.ghj.overt.mq.impl;

import com.bright.ghj.common.util.DateUtil;
import com.bright.ghj.overt.constant.RocketConstant;
import com.bright.ghj.overt.manager.DistZtManager;
import com.bright.ghj.overt.mq.MQProduceService;
import com.bright.ghj.overt.pojo.dto.DistDTO;
import com.bright.ghj.overt.pojo.po.primary.MqMessage;
import com.bright.ghj.overt.repository.primary.MqMessageRepository;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author: hxj
 * @Date: 2024/2/23 16:19
 */
@Service
@ConditionalOnBean(value = RocketMQTemplate.class)
@AllArgsConstructor
@Qualifier("rocketProduceService")
public class RocketProduceServiceImpl implements MQProduceService {

    private final RocketMQTemplate rocketMQTemplate;
    private final MqMessageRepository mqMessageRepository;
    private final DistZtManager distZtManager;

//    public void configureRetry() {
//        // 获取RocketMQ的生产者客户端
//        DefaultMQProducer producer = rocketMQTemplate.getProducer();
//        // 设置发送失败时的重试次数为5
//        producer.setRetryTimesWhenSendFailed(5);
//        // 设置发送失败时重试另一个Broker
//        producer.setRetryAnotherBrokerWhenNotStoreOK(true);
//        // 其他生产者配置...
//    }


    @Override
    public void sendMessage(MqMessage mqMessage) {

//        configureRetry();

        DistDTO dist = distZtManager.getDistByDistNoByCache(mqMessage.getDistNo());
        if (dist != null) {
            mqMessage.setDistName(dist.getDistName());
        }
        switch (mqMessage.getTopicType()){
            case RocketConstant.TOPIC_ACCESS_IMPORT:
                mqMessage.setTopicName(RocketConstant.TOPIC_ACCESS_IMPORT_NAME);
                break;



            default:
        }

        //默认是未消费且可用的消息
        mqMessage.setOkFlag(false);
        mqMessage.setRunFlag(true);
        mqMessage.setCreatedBy(mqMessage.getUsername());
        mqMessage.setCreatedTime(DateUtil.getCurrDate());
        MqMessage result = mqMessageRepository.save(mqMessage);
        if(Objects.isNull(result)){
            throw new RuntimeException("消息保存异常！");
        }
        rocketMQTemplate.convertAndSend(RocketConstant.TOPIC_CONSUMER, result);
    }


}
